/**
 * 各种画echarts图表的方法都封装在这里
 * 注意：这里echarts没有采用按需引入的方式，只是为了方便学习
 */

import echarts from 'echarts'
window.chart = {}
let screenWidth = null
let allScreenWith = document.getElementById('app').clientWidth
console.log('allScreenWith', allScreenWith)

// window.onload = function () {
//   screenWidth = document.getElementById('right-body').clientWidth
//   // console.log('screenWidth', screenWidth.clientWidth)
// }
window.onload = function () {
  let timer = setInterval(function () {
    if (document.getElementById('right-body')) {
      screenWidth = document.getElementById('right-body').clientWidth
      clearInterval(timer)
    }
  }, 500)
}
const install = function (Vue) {
  Object.defineProperties(Vue.prototype, {
    $chart: {
      get () {
        return {
          //
          open_user: function (id, map, arr) {
            console.log(map, arr)
            this.chart = echarts.init(document.getElementById(id))
            this.chart.clear()

            const optionData = {
              grid: {
                left: '0%',
                right: '1%',
                bottom: '1%',
                top: '5%',
                containLabel: true
              },
              tooltip: {
                trigger: 'axis'
                // axisPointer: {
                //   type: 'cross',
                //   label: {
                //     backgroundColor: '#2f4554'
                //   }
                // }
              },
              xAxis: {
                type: 'category',
                data: map
              },
              yAxis: {
                // name: '数量 (个)',
                type: 'value',
                minInterval: 1,
                nameTextStyle: {
                  padding: [0, 0, 0, 10]
                }

              },
              series: [{
                data: arr,
                barMaxWidth: '30',
                type: 'bar',
                itemStyle: {
                  color: function (params) {
                    var colorList = ['#5c8d82', '#7abadf', '#a650bb', '#e3724e']
                    return colorList[params.dataIndex]
                    // color: '#15d6ba'
                  }
                }
              }]
            }

            this.chart.setOption(optionData)
            chartResize(this.chart, 'open_user')
          },
          // 订购渠道
          open_channel: function (id, arr, arrData, cb) {
            const that = this
            this.chart = echarts.init(document.getElementById(id))
            this.chart.clear()
            this.chart.hideLoading()
            let selected = {}
            console.log(arrData)
            arrData.forEach((ele,index) => {
              if (ele.value == 0) {
                selected[ele.name] = false
              } else {
                selected[ele.name] = true
              }
            })
            console.log(selected)
            const optionData = {
              grid: {
                // left: '0',
                // right: '0',
                // bottom: '0%',
                // top: '0%',
                containLabel: true
              },

              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b} : {c} ({d}%)',
                confine: true
              },
              legend: {
                top: '5%',
                // right: 0,
                // orient: 'vertical',
                data: arr,
                selected: selected
              },
              series: [{
                name: '订购渠道',
                type: 'pie',
                minAngle: 5,
                radius: [30, 60],
                roseType: 'area',
                center: ['50%', '60%'],
                avoidLabelOverlap: true,
                data: arrData,
                itemStyle: {
                  color: function (params) {
                    var colorList = ['#D67B80', '#38C7C8', '#5EB2ED', '#FDB984', '#b6a4d9', '#c267be', '#36b638', '#5c88d2', '#e361a2', '#a650bb']
                    return colorList[params.dataIndex]
                    // color: '#15d6ba'
                  }
                },
                label: {
                  // fontSize: 10,
                  // position: 'inside'
                  // alignTo: 'labelLine',
                  formatter (v) {
                    let text = v.name
                    let percent = v.percent
                    let value = v.value
                    // return text + ': ' + value + ' (' + percent + '%)'
                    console.log('screenWidth', screenWidth, allScreenWith)
                    if ((screenWidth && screenWidth < 1600) || allScreenWith < 1800) {
                      return text.length < 3
                        ? text + ': ' + value + ' (' + percent + '%)'
                        : `${text.slice(0,8)}: \n`  + value + ' (' + percent + '%)'
                    } else {
                      return text + ': '+ value + ' (' + percent + '%)'
                    }
                  }
                },
                labelLine: {
                  // length: 3,
                  // length2: 4
                }
              }]
            }
            this.chart.setOption(optionData)
            chartResize(this.chart, 'open_channel')
          },
          // 日活跃用户数
          uv: function (id, date, num, isDet) {
            this.chart = echarts.init(document.getElementById(id))
            this.chart.clear()
            let startTime = new Date(date[0]).getTime()
            let endTime = new Date(date[date.length - 1]).getTime()
            let total = endTime - startTime
            let day = parseInt(total / (24 * 60 * 60) / 1000)
            const optionData = {
              tooltip: {
                trigger: 'axis'
                // axisPointer: {
                //   type: 'cross',
                //   label: {
                //     backgroundColor: '#2f4554'
                //   }
                // }
              },
              grid: {
                left: '5%',
                right: '5%',
                bottom: '8%',
                top: '5%',
                // x: -10,
                containLabel: true
              },
              xAxis: {
                // name: '日期',
                nameLocation: 'end',
                type: 'category',
                nameTextStyle: {
                  padding: [60, 0, 0, 0]
                },
                nameGap: '-20',
                data: date,
                axisLabel: {
                  formatter: function (value, index) {
                    const arr = value.split('-')
                    return arr[1] + '-' + arr[2]
                  }
                }
              },
              yAxis: {
                // name: '活跃用户数',
                type: 'value',
                minInterval: 1,
                nameTextStyle: {
                  padding: [0, 0, 0, 40]
                }
              },

              series: [{
                data: num,
                type: 'line',
                smooth: true,
                lineStyle: {
                  color: '#FDB984'
                },
                itemStyle: {
                  color: '#FDB984'
                }
              }]
            }
            if (isDet && day > 31) {
              optionData.dataZoom = [{
                id: 'dataZoomX',
                type: 'slider',
                xAxisIndex: [0],
                filterMode: 'filter',
                start: 100 - (31 / day * 100),
                end: 100,
                right: '9%',
                left: '7%'
              }
                // {
                //   id: 'dataZoomX1',
                //   type: 'inside',
                //   xAxisIndex: [0],
                //   filterMode: 'filter',
                //   start: 70,
                //   end: 100
                // }
              ]
              optionData.grid.left = '0%'
              optionData.grid.bottom = '12%'
              optionData.grid.right = '1%'
              optionData.grid.top = '6%'
            }
            this.chart.setOption(optionData)
            chartResize(this.chart, 'uv')
          },
          // 日注册用户数
          day_user: function (id, date, num, isDet) {
            this.chart = echarts.init(document.getElementById(id))
            this.chart.clear()
            let startTime = new Date(date[0]).getTime()
            let endTime = new Date(date[date.length - 1]).getTime()
            let total = endTime - startTime
            let day = parseInt(total / (24 * 60 * 60) / 1000)
            const optionData = {
              tooltip: {
                trigger: 'axis'
                // axisPointer: {
                //   type: 'cross',
                //   label: {
                //     backgroundColor: '#2f4554'
                //   }
                // }
              },
              grid: {
                left: '5%',
                right: '5%',
                bottom: '8%',
                top: '5%',
                // x: -10,
                containLabel: true
              },
              xAxis: {
                // name: '日期',
                nameLocation: 'end',
                type: 'category',
                nameTextStyle: {
                  padding: [60, 0, 0, 0]
                },
                nameGap: '-20',
                data: date,
                axisLabel: {
                  formatter: function (value, index) {
                    const arr = value.split('-')
                    return arr[1] + '-' + arr[2]
                  }
                }
              },
              yAxis: {
                // name: '活跃用户数',
                type: 'value',
                minInterval: 1,
                nameTextStyle: {
                  padding: [0, 0, 0, 40]
                }
              },

              series: [{
                data: num,
                type: 'line',
                smooth: true,
                lineStyle: {
                  color: '#b6a4d9'
                },
                itemStyle: {
                  color: '#b6a4d9'
                }
              }]
            }
            if (isDet && day > 31) {
              optionData.dataZoom = [{
                id: 'dataZoomX',
                type: 'slider',
                xAxisIndex: [0],
                filterMode: 'filter',
                start: 100 - (31 / day * 100),
                end: 100,
                right: '9%',
                left: '7%'
              }
                // {
                //   id: 'dataZoomX1',
                //   type: 'inside',
                //   xAxisIndex: [0],
                //   filterMode: 'filter',
                //   start: 70,
                //   end: 100
                // }
              ]
              optionData.grid.left = '0%'
              optionData.grid.bottom = '12%'
              optionData.grid.right = '1%'
              optionData.grid.top = '6%'
            }
            this.chart.setOption(optionData)
            chartResize(this.chart, 'uv')
          },

          open_product: function (id, arr, cb) {
            this.chart = echarts.init(document.getElementById(id))
            this.chart.clear()
            const optionData = {
              grid: {
                left: '3%',
                right: '3%',
                bottom: '1%',
                top: '5%',
                containLabel: true
              },
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)',
                confine: true
              },
              series: [{
                name: '开通套餐',
                type: 'pie',
                radius: ['30%', '50%'],
                // avoidLabelOverlap: false,
                data: arr,
                labelLine: {
                  normal: {
                    length: 6,
                    length2: 6
                  }
                },
                itemStyle: {
                  color: function (params) {
                    var colorList = ['#D67B80', '#38C7C8', '#5EB2ED', '#FDB984', '#b6a4d9', '#c267be', '#36b638', '#5c88d2', '#e361a2', '#a650bb']
                    return colorList[params.dataIndex]
                    // color: '#15d6ba'
                  }
                }
              }]
            }
            this.chart.setOption(optionData)
            this.chart.on('click', function (params) {
              cb()
            })
          },
          // 收益分析
          income_analysis: function (id, date, value1, isDet) {
            this.chart = echarts.init(document.getElementById(id))
            this.chart.clear()
            let startTime = new Date(date[0]).getTime()
            let endTime = new Date(date[date.length - 1]).getTime()
            let total = endTime - startTime
            let day = parseInt(total / (24 * 60 * 60) / 1000)
            const optionData = {
              tooltip: {
                trigger: 'axis',
                // axisPointer: {
                //   type: 'cross',
                //   label: {
                //     backgroundColor: '#6a7985'
                //   }
                // }
                formatter: function (e) {
                  // console.log('营收（元）', e[0])
                  return e[0].axisValue + '<br>' + e[0].marker + e[0].seriesName + '：' + (e[0].value / 100).toFixed(2)
                }
              },
              grid: {
                left: '1%',
                right: '3%',
                bottom: '3%',
                top: '8%',
                containLabel: true
              },
              xAxis: {
                // name: '日期',
                nameLocation: 'end',
                nameTextStyle: {
                  padding: [60, 0, 0, 0]
                },
                nameGap: '-20',
                type: 'category',
                axisLabel: {
                  // rotate: 60,
                  formatter: function (value, index) {
                    const arr = value.split('-')
                    return arr[1] + '-' + arr[2]
                  }
                },
                data: date
              },
              yAxis: [{
                type: 'value',
                name: '',
                position: 'left',
                minInterval: 1,
                axisLabel: {
                  formatter: function (value, index) {
                    // console.log('营收（元）', (value / 100).toFixed(2))
                    return value / 100
                  }
                }
              }],
              series: [{
                name: '营收（元）',
                data: value1,
                barWidth: 35,
                yAxisIndex: 0,
                type: 'line',
                smooth: true,
                // label: {
                //   formatter: function (value, index) {
                //     // console.log('营收（元）', (value / 100).toFixed(2))
                //     return value / 100
                //   }
                // },
                itemStyle: {
                  color: '#668C8C'
                }

                // areaStyle: {
                //   // color: '#61a0a8'
                // }
              }]
            }
            if (isDet && day > 31) {
              optionData.dataZoom = [{
                id: 'dataZoomX',
                type: 'slider',
                xAxisIndex: [0],
                filterMode: 'filter',
                start: 100 - (31 / day * 100),
                end: 100,
                right: '6%',
                left: '5%'
              }
              ]
              optionData.grid.bottom = '12%'
              optionData.grid.left = '0%'
              optionData.grid.right = '3%'
              optionData.grid.top = '6%'
            }
            this.chart.setOption(optionData)
            chartResize(this.chart, 'income_analysis')
          },
          // 日访问数统计
          pv: function (id, map, arr) {
            console.log(map, arr)
            this.chart = echarts.init(document.getElementById(id))
            this.chart.clear()

            const optionData = {
              grid: {
                left: '0%',
                right: '1%',
                bottom: '1%',
                top: '5%',
                containLabel: true
              },
              tooltip: {
                trigger: 'axis'
                // axisPointer: {
                //   type: 'cross',
                //   label: {
                //     backgroundColor: '#2f4554'
                //   }
                // }
              },
              xAxis: {
                type: 'category',
                data: map,
                axisLabel: {
                  formatter: function (value, index) {
                    const arr = value.split('-')
                    return arr[1] + '-' + arr[2]
                  }
                }
              },
              yAxis: {
                // name: '数量 (个)',
                type: 'value',
                minInterval: 1,
                nameTextStyle: {
                  padding: [0, 0, 0, 10]
                }

              },
              series: [{
                data: arr,
                barMaxWidth: '30',
                type: 'bar',
                itemStyle: {
                  color: '#D67B80'
                }
              }]
            }

            this.chart.setOption(optionData)
            chartResize(this.chart, 'pv')
          },
          // 日业务订购情况
          reception: function (id, date,legend, value, isDet) {
            this.chart = echarts.init(document.getElementById(id))
            this.chart.clear()
            let startTime = new Date(date[0]).getTime()
            let endTime = new Date(date[date.length - 1]).getTime()
            let total = endTime - startTime
            let day = parseInt(total / (24 * 60 * 60) / 1000)
            // let colors = ['#6F8F8A', '#4D9ACF','#8F8E6F','#7A6B8F','#8F796F','#DF9F34','#8F6B68','#8F576B','#47A757','#E36F93']
            let colors = ['#D67B80', '#38C7C8', '#5EB2ED', '#FDB984', '#b6a4d9', '#c267be', '#36b638', '#5c88d2', '#e361a2', '#DF9F34']
            const optionData = {
              tooltip: {
                trigger: 'axis',
                // formatter: function (e) {
                //   // console.log('营收（元）', e[0])
                //   return e[0].axisValue + '<br>' + e[0].marker + e[0].seriesName + '：' + (e[0].value)
                // }
              },
              legend: {
                data: legend,
                boundaryGap: false,
                top: 0,
                right: '13%',
                show: isDet
             },
              grid: {
                left: '1%',
                right: '3%',
                bottom: '0%',
                top: '20%',
                containLabel: true
              },
              xAxis: {
                // name: '日期',
                nameLocation: 'end',
                nameTextStyle: {
                  padding: [60, 0, 0, 0]
                },
                nameGap: '-20',
                type: 'category',
                axisLabel: {
                  // rotate: 60,
                  formatter: function (value, index) {
                    const arr = value.split('-')
                    return arr[1] + '-' + arr[2]
                  }
                },
                data: date
              },
              yAxis: {
                type: 'value',
                // name: '数量',
                position: 'left',
                minInterval: 1,
                boundaryGap:false,
                axisLabel: {
                  formatter: function (value, index) {
                    // console.log('营收（元）', (value / 100).toFixed(2))
                    return value
                  }
                }
              },
              series: []
            }
            let series = []
            legend.forEach((ele,index) => {
              series.push({
                name: ele,
                data: value[index],
                type: 'line',
                smooth: true,
                itemStyle: {
                  color: colors[index]
                }
              })
            })
            optionData.series = series
            if (isDet) {
              optionData.grid.top = '10%'
              optionData.legend.right = '3%'
            }
            if (isDet && day > 31) {
              optionData.dataZoom = [{
                id: 'dataZoomX',
                type: 'slider',
                xAxisIndex: [0],
                filterMode: 'filter',
                start: 100 - (365 / day * 100),
                end: 100,
                right: '6%',
                left: '5%'
              }
              ]
              optionData.grid.bottom = '12%'
              optionData.grid.left = '0%'
              optionData.grid.right = '3%'
              optionData.grid.top = '5%'
            }
            this.chart.setOption(optionData)
            chartResize(this.chart, 'income_analysis')
          }
        }
      }
    }
  })
}

function chartResize (chart, name) {
  window.addEventListener('resize', function (e) {
    let outerWidth = e.currentTarget.outerWidth
    console.log('outerWidth', outerWidth)
    // if (name == 'open_channel')
    chart.resize()
    screenWidth = document.getElementById('right-body').clientWidth
  })
  window.chart[name] = chart
}
export default {
  install
}
